package com.leesche.zcsp.node.app.v1.controller.operate;

import com.leesche.zcsp.node.app.v1.controller.admin.AppAdminController;
import com.leesche.zcsp.node.app.v1.vo.PlaceDeviceTypesVo;
import com.leesche.zcsp.node.app.v1.vo.PlaceDevicesVo;
import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.service.PubDevGiftStockService;
import com.leesche.zcsp.node.web.service.PubDevicePayDetailStatisticsService;
import com.leesche.zcsp.node.web.service.PubDeviceService;
import com.leesche.zcsp.node.web.service.PubPlaceService;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by kaider on 2016/11/15.
 */
@Controller
@RequestMapping("/app/v1/operate/search")
public class AppSearchController extends AppAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AppSearchController.class);

    @Autowired
    private PubPlaceService placeService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private PubDevicePayDetailStatisticsService detailStatisticsService;
    @Autowired
    private PubDevGiftStockService giftStockService;
    @Autowired
    private NetService netService;

    /**
     * 初始化查询设备搜索
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchView", method = RequestMethod.POST)
    public Map<String,Object> searchDeviceView(
            QueryPubPlaceCondition placeCondition,
            QueryPubDeviceCondition deviceCondition
    ){
        try {
            Map<String,Object> map = new HashMap<String,Object>();
//            Long adminId = 1L;
            Long adminId = getAdminId();
            placeCondition.setAdminId(adminId);
            deviceCondition.setAdminId(adminId);

            List<PubPlaceDto> placeDtoList = placeService.findPubPlaceList(placeCondition);
            List<InfoDeviceDto> deviceDtoList = deviceService.findDeviceList(deviceCondition);
            map.put("placeDtoList",placeDtoList);
            map.put("deviceDtoList",deviceDtoList);

            return WebResult.success().put("data",map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 场地查询设备列表
     * @param placeId
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchPlace2Device", method = RequestMethod.POST)
    public Map<String,Object> searchPlace2Device(
            Long placeId,
            QueryPubDeviceCondition deviceCondition
    ){
        try {
//            Long adminId = 1L;
            Long adminId = getAdminId();
            deviceCondition.setAdminId(adminId);
            deviceCondition.setPlaceId(placeId);
            List<InfoDeviceDto> deviceDtoList = deviceService.findDeviceList(deviceCondition);

            return WebResult.success().put("data",deviceDtoList).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备搜索结果v2
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDeviceNew", method = RequestMethod.POST)
    public Map<String,Object> searchDeviceNew(
            QueryPubDeviceCondition deviceCondition,
            QueryPubPlaceCondition placeCondition
    ){
//        Long adminId = 1L;
        Long adminId = getAdminId();
        deviceCondition.setAdminId(adminId);
        placeCondition.setAdminId(adminId);
        Map<String,Object> map = new HashMap<String,Object>();

        try {
            if(StringUtils.isNotBlank(deviceCondition.getImme()) ||
                    StringUtils.isNotBlank(deviceCondition.getDeviceshortcode()) ||
                    deviceCondition.getDeviceId()!=0){
                //设备列表
                LOGGER.info("设备列表分类");
                List<InfoDeviceDto> deviceDtoList = deviceService.findDeviceList(deviceCondition);
                return WebResult.success().put("data",deviceDtoList).toMap();
            }else{
                if(deviceCondition.getPlaceId()==0 && deviceCondition.getDeviceId()==0){
                    //所有场地
                    LOGGER.info("所有场地分类");
                    //场地
                    List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
                    List<PlaceDevicesVo> placeDevicesList = new ArrayList<PlaceDevicesVo>();
                    //场地设备
                    for(PubPlaceDto dto : placeList){
                        PlaceDevicesVo vo = new PlaceDevicesVo();
                        vo.setPlaceId(dto.getPlaceid());
                        vo.setPlaceName(dto.getAddress());
                        deviceCondition.setPlaceId(dto.getPlaceid());
                        List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);
                        vo.setOnlineList(deviceList);
                        placeDevicesList.add(vo);
                    }

                    map.put("placeDevicesList",placeDevicesList);
                    return WebResult.success().put("data",map).toMap();
                }else{
                    //设备类型
                    LOGGER.info("设备类型分类");
                    PlaceDeviceTypesVo vo = new PlaceDeviceTypesVo();
                    placeCondition.setPlaceId(deviceCondition.getPlaceId());
                    PubPlaceDto dto = placeService.findByCondition(placeCondition);
                    vo.setPlaceId(dto.getPlaceid());
                    vo.setPlaceName(dto.getAddress());

                    deviceCondition.setPlaceId(deviceCondition.getPlaceId());
                    deviceCondition.setAdminId(Long.valueOf(dto.getAdminid()));

                    List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

                    //在线设备
                    List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
                    //离线设备
                    List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
                    //禁用设备
                    List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
                    //故障设备
                    List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();

                    if(deviceList.size()>0){
                        Map<String, String> deviceOnlines = netService.isOnlineBatch(getDeviceNames(deviceList));

                        for(InfoDeviceDto deviceDto : deviceList){
                            if (deviceOnlines.get(deviceDto.getImme()) != null && deviceOnlines.get(deviceDto.getImme()).equalsIgnoreCase("ONLINE")) {
                                deviceDto.setIsOnline(1);
                            } else {
                                deviceDto.setIsOnline(2);
                            }
                            if (deviceDto.getIsOnline().equals(1) && deviceDto.getState().equals(2)) {
                                disabled.add(deviceDto);
                            } else if (deviceDto.getIsOnline().equals(1)) {
                                online.add(deviceDto);
                            } else if (deviceDto.getIsOnline().equals(2)) {
                                offline.add(deviceDto);
                            } else {
                                fault.add(deviceDto);
                            }
                        }
                    }

                    map.put("online", online);
                    map.put("offline", offline);
                    map.put("disabled", disabled);
                    map.put("fault", fault);
                    map.put("placeDevices",vo);
                    return WebResult.success().put("data",map).toMap();
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 设备搜索结果v1
     * @param deviceCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchDevice", method = RequestMethod.POST)
    public Map<String,Object> searchDevice(
            QueryPubDeviceCondition deviceCondition,
            QueryPubPlaceCondition placeCondition
    ){
//        Long adminId = 1L;
        Long adminId = getAdminId();
        deviceCondition.setAdminId(adminId);
        placeCondition.setAdminId(adminId);
        Map<String,Object> map = new HashMap<String,Object>();

        try {
            if(StringUtils.isNotBlank(deviceCondition.getImme()) ||
               StringUtils.isNotBlank(deviceCondition.getDeviceshortcode()) ||
               deviceCondition.getDeviceId()!=0){
                //设备列表
                LOGGER.info("设备列表分类");
                List<InfoDeviceDto> deviceDtoList = deviceService.findDeviceList(deviceCondition);
                return WebResult.success().put("data",deviceDtoList).toMap();
            }else{
                if(deviceCondition.getPlaceId()==0 && deviceCondition.getDeviceId()==0){
                    //所有场地
                    LOGGER.info("所有场地分类");
                    //场地
                    List<PubPlaceDto> placeList = placeService.findPubPlaceList(placeCondition);
                    List<PlaceDevicesVo> placeDevicesList = new ArrayList<PlaceDevicesVo>();
                    //场地设备
                    for(PubPlaceDto dto : placeList){
                        PlaceDevicesVo vo = new PlaceDevicesVo();
                        vo.setPlaceId(dto.getPlaceid());
                        vo.setPlaceName(dto.getAddress());
                        deviceCondition.setPlaceId(dto.getPlaceid());
                        List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);
                        vo.setOnlineList(deviceList);
                        placeDevicesList.add(vo);
                    }

                    map.put("placeDevicesList",placeDevicesList);
                    return WebResult.success().put("data",map).toMap();
                }else{
                    //设备类型
                    LOGGER.info("设备类型分类");
                    PlaceDeviceTypesVo vo = new PlaceDeviceTypesVo();
                    placeCondition.setPlaceId(deviceCondition.getPlaceId());
                    PubPlaceDto dto = placeService.findByCondition(placeCondition);
                    vo.setPlaceId(dto.getPlaceid());
                    vo.setPlaceName(dto.getAddress());

                    deviceCondition.setPlaceId(deviceCondition.getPlaceId());
                    deviceCondition.setAdminId(Long.valueOf(dto.getAdminid()));
                    List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

                    //礼品机
                    List<InfoDeviceDto> giftList = new ArrayList<InfoDeviceDto>();
                    //兑币机
                    List<InfoDeviceDto> currencyList = new ArrayList<InfoDeviceDto>();
                    //娃娃机
                    List<InfoDeviceDto> dollList = new ArrayList<InfoDeviceDto>();
                    //礼品兑换机
                    List<InfoDeviceDto> giftExchangeList = new ArrayList<InfoDeviceDto>();

                    for(InfoDeviceDto deviceDto : deviceList){
                        switch (deviceDto.getDeviceTypeId().intValue()){
                            //礼品
                            case 1:
                                giftList.add(deviceDto);
                                break;
                            //兑币
                            case 2:
                                currencyList.add(deviceDto);
                                break;
                            //娃娃
                            case 3:
                                dollList.add(deviceDto);
                                break;
                            //礼品兑换
                            case 4:
                                giftExchangeList.add(deviceDto);
                                break;
                            default:
                                break;
                        }
                    }
                    vo.setCurrencyList(currencyList);
                    vo.setDollList(dollList);
                    vo.setGiftList(giftList);
                    vo.setGiftExchangeList(giftExchangeList);
                    map.put("placeDevices",vo);
                    return WebResult.success().put("data",map).toMap();
                }
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 账目查询结果
     * @param deviceCondition
     * @param statisticsCondition
     * @param placeCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/searchAccount", method = RequestMethod.POST)
    public Map<String,Object> searchAccount(
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            QueryPubPlaceCondition placeCondition,
            QueryPubDevGiftStockCondition giftStockCondition
    ){
        Map<String,Object> map = new HashMap<String,Object>();
        PubDevicePayDetailStatisticsDto detailStatisticsDto;
        String placeName="";
        String deviceName="";
        try {
//            Long adminId = 1L;
            Long adminId = getAdminId();
            deviceCondition.setAdminId(adminId);
            placeCondition.setAdminId(adminId);
            statisticsCondition.setUserId(adminId);
            giftStockCondition.setAdminId(adminId);
            if(deviceCondition.getPlaceId()==0 && deviceCondition.getDeviceId()==0){
                detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);

                detailStatisticsDto = getGiftCount(detailStatisticsDto,placeCondition,giftStockCondition);
                placeName = "全场地全设备";
            }else{
                if(deviceCondition.getDeviceId()!=0){
                    //某个场地某个设备
                    InfoDeviceDto deviceDto = deviceService.findInfoDevice(deviceCondition);
                    if(deviceDto!=null){
                        placeName = deviceDto.getAddress();
                        deviceName = deviceDto.getDeviceName();
                    }
                    detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
                    detailStatisticsDto = getGiftCount(detailStatisticsDto,placeCondition,giftStockCondition);
                }else{
                    //某个场地所有设备
                    PubPlaceDto placeDto = placeService.findByCondition(placeCondition);
                    detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
                    detailStatisticsDto = getGiftCount(detailStatisticsDto,placeCondition,giftStockCondition);
                    placeName = placeDto.getAddress();
                }
            }
            map.put("detailStatisticsDto",detailStatisticsDto);
            map.put("stime",statisticsCondition.getStime());
            map.put("etime",statisticsCondition.getEtime());
            map.put("placeName",placeName);
            map.put("deviceName",deviceName);
            return WebResult.success().put("data",map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 获取设备礼品库存总数
     * @param placeCondition
     * @param giftStockCondition
     * @return
     */
    private PubDevicePayDetailStatisticsDto getGiftCount(PubDevicePayDetailStatisticsDto detailStatisticsDto,QueryPubPlaceCondition placeCondition,QueryPubDevGiftStockCondition giftStockCondition){
        List<Long> placeDeviceIds = new ArrayList<Long>();

        if(placeCondition.getPlaceId()==0 && placeCondition.getDeviceId()==0 ){
            //全场地全设备
            placeDeviceIds = placeService.findPlaceDeviceIds(placeCondition);
        }else {
            if(placeCondition.getDeviceId()!=0){
                //某台设备
                placeDeviceIds.add(placeCondition.getDeviceId());
            }else {
                //某场地全设备
                placeDeviceIds = placeService.findPlaceDeviceIds(placeCondition);
            }
        }

        if(placeDeviceIds.size()>0){
            giftStockCondition.setDeviceIds(placeDeviceIds);
            Integer giftCount = giftStockService.getGiftCount(giftStockCondition);
            if(detailStatisticsDto!=null){
                detailStatisticsDto.setGiftCount(giftCount);
            }else{
                detailStatisticsDto = new PubDevicePayDetailStatisticsDto();
                detailStatisticsDto.setGiftCount(giftCount);
            }
            return detailStatisticsDto;
        }else {
            if(detailStatisticsDto!=null){
                detailStatisticsDto.setGiftCount(0);
            }else{
                detailStatisticsDto = new PubDevicePayDetailStatisticsDto();
                detailStatisticsDto.setGiftCount(0);
            }
            return detailStatisticsDto;
        }
    }

    private List<String> getDeviceNames(List<InfoDeviceDto> lists) {
        List<String> deviceNames = new ArrayList<String>();
        if (lists != null) {
            for (InfoDeviceDto infoDeviceDto : lists) {
                deviceNames.add(infoDeviceDto.getImme());
            }
        }
        return deviceNames;
    }

}
